package util.hibernate;

import java.io.File;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	
	public static String appHome = "No";
	private static SessionFactory sessionFactory;
	private static final ThreadLocal threadSession = new ThreadLocal();
	private static final ThreadLocal threadTransaction = new ThreadLocal();
	
	// Create the initial SessionFactory from default config files
	public static void configure(){
		
		try {
			String path_properties = appHome+File.separatorChar+"hibernate.cfg.xml";
			Configuration configuration = new Configuration();
			configuration.addFile(path_properties);
			sessionFactory =configuration.configure().buildSessionFactory();
		
		} catch (Throwable ex) {		
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	
	public static SessionFactory getSessionFactory() {
		if (sessionFactory==null) configure();
		return sessionFactory;
	}
	
	public static Session getSession(){
		
		Session s = (Session) threadSession.get();
		
		if (s == null) {
			s = getSessionFactory().openSession();
			threadSession.set(s);
		}
		
		return s;
		
	}

}